package com.jmda.platform.repository.worklist.action;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jmda.platform.commom.SequenceService;
import com.jmda.platform.engine.mybatis.MybatisEngine;
import com.jmda.platform.repository.ResositoryException;
import com.jmda.platform.repository.RespositoryConstant;
import com.jmda.platform.repository.metadata.model.MetadataMapModel;
import com.jmda.platform.repository.metadata.service.MetadataService;
import com.jmda.platform.repository.worklist.model.ColumnModel;
import com.jmda.platform.repository.worklist.model.WorkListModel;
import com.jmda.platform.repository.worklist.service.WorkListService;
import com.jmda.platform.repository.worklist.util.CamelCaseUtils;
import com.jmda.platform.repository.worklist.util.WorkListColumnCommonMethod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/repository/worklist/columns")
public class WorkListColumnsController {

    @Resource
    MetadataService metadataService;
    @Resource
    WorkListService workListService;
    @Resource
    SequenceService seq;
    @Resource
    private WorkListColumnCommonMethod workListColumnOrder = null;

    @RequestMapping(value = "/getWorkListColumnsPage", method = {RequestMethod.POST, RequestMethod.GET})
    public String getWorkListColumnsPage(String id, ModelMap map) throws ResositoryException {
        WorkListModel model = workListService.get(id);
        map.put("id", id);
        map.put("name", model.getName());
        return "repository/worklist/Sys_Repository_WorkList_Columns";
    }

    @RequestMapping(value = "/getWorkListVirtualColumnsPage", method = {RequestMethod.POST, RequestMethod.GET})
    public String getWorkListVirtualColumnsPage(String id, ModelMap map) {
        map.put("id", id);
        return "repository/worklist/Sys_Repository_WorkList_Virtual_Columns";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/getWorkListColumnsJson", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getWorkListColumnsJson(String id) throws JsonProcessingException, ResositoryException {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> json = new HashMap<String, Object>();
        WorkListModel model = workListService.get(id);
        List<ColumnModel> list = model.getColumn();
        //兼容之前版本缺少字段类型
        for (ColumnModel columnModel : list) {
            if (columnModel.getColumn_type() == null || "".equalsIgnoreCase(columnModel.getColumn_type().trim())) {
                columnModel.setColumn_type("db");
            }
        }
        list = list == null ? new ArrayList<ColumnModel>() : list;
        if (list != null) {
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(Object o1, Object o2) {
                    if (((ColumnModel) o1).getOrderIndex() > ((ColumnModel) o2).getOrderIndex()) {

                        return 1;
                    }
                    if (((ColumnModel) o1).getOrderIndex() == ((ColumnModel) o2).getOrderIndex()) {
                        return 0;
                    }
                    return -1;
                }
            });
        }

        json.put("root", list);
        json.put("total", list == null ? 0 : list.size());
        return mapper.writeValueAsString(json);
    }

    @RequestMapping(value = "/openWorkListMetadataMapSelectPage", method = {RequestMethod.POST, RequestMethod.GET})
    public String openWorkListMetadataMapSelectPage(String id, ModelMap map) {
        map.put("id", id);
        return "repository/worklist/Sys_Repository_WorkList_Metadata_Select_Grid";
    }

    @Resource
    MybatisEngine mybatis;

    @RequestMapping(value = "/getWorListMetadataMapSelectJsonData", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getWorListMetadataMapSelectJsonData(String id) throws ResositoryException, JsonProcessingException {
        WorkListModel model = workListService.get(id);
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> json = new HashMap<String, Object>();
        List<MetadataMapModel> list = metadataService.getMetadataMapListBySql(mybatis.getMapperSql(model.getId(), RespositoryConstant.WORKLIST_RUNTIME_QUERY_LIST_ID));
        json.put("root", list);
        json.put("total", list == null ? 0 : list.size());
        return mapper.writeValueAsString(json);
    }

    @RequestMapping(value = "/addWorkListMetadataMap", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String addWorkListMetadataMap(String id, String selectJson) throws ResositoryException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<MetadataMapModel> selectFormMetadataMapList = mapper.readValue(selectJson, new TypeReference<ArrayList<MetadataMapModel>>() {
        });
        if (selectFormMetadataMapList != null && selectFormMetadataMapList.size() > 0) {
            WorkListModel workListModel = workListService.get(id);
            List<ColumnModel> workListColumnModellist = workListModel.getColumn();
            workListColumnModellist = workListColumnModellist == null ? new ArrayList<ColumnModel>() : workListColumnModellist;
            for (MetadataMapModel metadataMapModel : selectFormMetadataMapList) {
                boolean isOK = true;
                for (ColumnModel columnModel : workListColumnModellist) {
                    if (metadataMapModel.getTABLE_COLUMN_TYPE() == null || "".equalsIgnoreCase(metadataMapModel.getTABLE_COLUMN_TYPE().trim()) || "db".equalsIgnoreCase(metadataMapModel.getTABLE_COLUMN_TYPE())) {
                        if (columnModel.getColumnName().equals(metadataMapModel.getCOLUMN_LABEL()) && columnModel.getTalbelName().equals(metadataMapModel.getTABLE_NAME())) {
                            isOK = false;
                            break;
                        }
                    } else {
                        if (columnModel.getColumnName().equals(metadataMapModel.getCOLUMN_NAME())) {
                            isOK = false;
                            break;
                        }
                    }

                }
                if (isOK) {
                    ColumnModel columnModel = new ColumnModel();
                    columnModel.setId(seq.getUUID());
                    columnModel.setOrderIndex(0);
                    columnModel.setSupportFuzzySearch(false);
                    columnModel.setTalbelName(metadataMapModel.getTABLE_NAME());
                    columnModel.setTitle(metadataMapModel.getCOLUMN_TITLE());
                    columnModel.setWidth(new BigDecimal(0.1));
                    columnModel.setHidden(false);
                    columnModel.setPk(false);
                    columnModel.setColspan(0);
                    columnModel.setRowspan(0);
                    columnModel.setColumn_type((metadataMapModel.getTABLE_COLUMN_TYPE() == null || "".equalsIgnoreCase(metadataMapModel.getTABLE_COLUMN_TYPE().trim())) ? "db" : metadataMapModel.getTABLE_COLUMN_TYPE());
                    if (columnModel.getColumn_type().equalsIgnoreCase("db")) {
                        columnModel.setDbColumnName(CamelCaseUtils.toCamelCase(metadataMapModel.getCOLUMN_LABEL()));
                        columnModel.setColumnName(metadataMapModel.getCOLUMN_LABEL());
                    } else {
                        columnModel.setColumnName(metadataMapModel.getCOLUMN_NAME());
                    }
                    columnModel.setOrderIndex(workListService.getWorkListColumnNextIndex(workListModel));
                    workListColumnModellist.add(columnModel);
                }
            }
            workListModel.setColumn(workListColumnModellist);
            workListService.store(workListModel);
        }

        return "ok";
    }

    @RequestMapping(value = "/addWorkListMetadataVirtualMap", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String addWorkListMetadataVirtualMap(String id, String selectJson) throws ResositoryException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<MetadataMapModel> selectFormMetadataMapList = mapper.readValue(selectJson, new TypeReference<ArrayList<MetadataMapModel>>() {
        });
        int i = 0;
        if (selectFormMetadataMapList != null && selectFormMetadataMapList.size() > 0) {
            WorkListModel workListModel = workListService.get(id);
            List<ColumnModel> workListColumnModellist = workListModel.getColumn();
            workListColumnModellist = workListColumnModellist == null ? new ArrayList<ColumnModel>() : workListColumnModellist;
            for (MetadataMapModel metadataMapModel : selectFormMetadataMapList) {
                boolean isOK = true;
                for (ColumnModel columnModel : workListColumnModellist) {
                    if (columnModel.getColumnName().equals(metadataMapModel.getCOLUMN_NAME())) {
                        isOK = false;
                        break;
                    }
                }
                if (isOK) {
                    ColumnModel columnModel = new ColumnModel();
                    columnModel.setColumnName(metadataMapModel.getCOLUMN_LABEL());
                    columnModel.setId(seq.getUUID());
                    columnModel.setOrderIndex(0);
                    columnModel.setSupportFuzzySearch(false);
                    columnModel.setTalbelName(metadataMapModel.getTABLE_NAME());
                    columnModel.setTitle(metadataMapModel.getCOLUMN_TITLE());
                    columnModel.setWidth(new BigDecimal(0.1));
                    columnModel.setHidden(false);
                    columnModel.setPk(false);
                    columnModel.setColspan(0);
                    columnModel.setRowspan(0);
                    columnModel.setColumn_type((metadataMapModel.getTABLE_COLUMN_TYPE() == null || "".equalsIgnoreCase(metadataMapModel.getTABLE_COLUMN_TYPE().trim())) ? "db" : metadataMapModel.getTABLE_COLUMN_TYPE());
                    columnModel.setOrderIndex(workListService.getWorkListColumnNextIndex(workListModel)+i);
                    workListColumnModellist.add(columnModel);
                    i = i+1;
                }
            }
            workListModel.setColumn(workListColumnModellist);
            workListService.store(workListModel);
        }

        return "ok";
    }

    @RequestMapping(value = "/saveWorkListColumn", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String saveWorkListColumn(String id, String datas) throws ResositoryException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        List<ColumnModel> newColumnList = mapper.readValue(datas, new TypeReference<ArrayList<ColumnModel>>() {
        });
        if (newColumnList != null && newColumnList.size() > 0) {
            WorkListModel workListModel = workListService.get(id);
            List<ColumnModel> workListColumnModellist = workListModel.getColumn();
            workListColumnModellist = workListColumnModellist == null ? new ArrayList<ColumnModel>() : workListColumnModellist;
            for (ColumnModel column : workListColumnModellist) {
                for (ColumnModel newColumnModel : newColumnList) {
                    if (column.getId().equals(newColumnModel.getId())) {
                        column.setSupportFuzzySearch(newColumnModel.isSupportFuzzySearch());
                        column.setTitle(newColumnModel.getTitle());
                        column.setWidth(newColumnModel.getWidth());
                        column.setHotlinkName(newColumnModel.getHotlinkName());
                        column.setHotlinkParam(newColumnModel.getHotlinkParam());
                        column.setHidden(newColumnModel.isHidden());
                        column.setPk(newColumnModel.isPk());
                        column.setColumn_align(newColumnModel.getColumn_align());
                        column.setFormatter(newColumnModel.getFormatter());
                        column.setSortable(newColumnModel.isSortable());
                        column.setDbColumnName(newColumnModel.getColumnName());
                        column.setPk(newColumnModel.isPk());
                        column.setColspan(newColumnModel.getColspan());
                        column.setRowspan(newColumnModel.getRowspan());
                        column.setRow_symbol(newColumnModel.getRow_symbol());
                        if (newColumnModel.getRef_params() != null && newColumnModel.getRef_params().trim().length() > 0) {
                            column.setRef_type("redis");
                            column.setRef_params(newColumnModel.getRef_params());
                        } else {
                            column.setRef_type(null);
                            column.setRef_params(null);
                        }

                    }
                }
            }
            workListService.store(workListModel);
        }

        return "ok";
    }

    @RequestMapping(value = "/removeWorkListColumn", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String removeWorkListColumn(String id, String ids) throws ResositoryException, IOException {
        String[] idArray = ids.split(",");
        if (idArray != null && idArray.length > 0) {
            WorkListModel workListModel = workListService.get(id);
            List<ColumnModel> workListColumnModellist = workListModel.getColumn();
            List<ColumnModel> newworkListColumnModellist = new ArrayList<ColumnModel>();
            for (ColumnModel column : workListColumnModellist) {
                boolean isOk = true;
                for (int i = 0; i < idArray.length; i++) {
                    if (column.getId().equals(idArray[i])) {
                        isOk = false;
                        break;
                    }
                }
                if (isOk) {
                    newworkListColumnModellist.add(column);
                }
            }
            workListModel.setColumn(newworkListColumnModellist);
            workListService.store(workListModel);
        }
        return "ok";
    }

    /**
     * 拖动排序
     *
     * @param sourceId
     * @param targetId
     * @param id
     * @return
     */
    @RequestMapping(value = "/sortGird", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String sortGirdMap(String sourceId, String targetId, String id) {
        return workListColumnOrder.workListColumnOrder(id, sourceId, targetId);
    }
    
    /**
     * 重新排序
     * @param id
     * @return
     * @throws ResositoryException
     * @throws IOException
     */
    @RequestMapping(value = "/afreshSortFormMetadataMap", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String afreshSortFormMetadataMap(String id) throws ResositoryException, IOException {
    	WorkListModel workListModel = workListService.get(id);
    	List<ColumnModel> columnModelList = workListModel.getColumn();
    	int i=1;
        for (ColumnModel columnModel : columnModelList) {
        	columnModel.setOrderIndex(i);
        	i=i+1;
        }
        return "ok";
    }
}
